from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime
from database import get_db
from models import Drone, User
from schemas import DroneCreate, DroneUpdate, DroneSchema, ResponseModel, PaginatedResponse
from api.deps import get_current_active_user, get_current_superuser

router = APIRouter()

@router.get("", response_model=ResponseModel[PaginatedResponse[DroneSchema]])
def get_drones(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="无人机名称搜索"),
    serial_number: Optional[str] = Query(None, description="序列号搜索"),
    status: Optional[str] = Query(None, description="状态过滤"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取无人机列表"""
    query = db.query(Drone)
    
    if name:
        query = query.filter(Drone.name.contains(name))
    
    if serial_number:
        query = query.filter(Drone.serial_number.contains(serial_number))
    
    if status:
        query = query.filter(Drone.status == status)
    
    # 计算总数
    total = query.count()
    
    # 分页
    drones = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=drones
        )
    )

@router.get("/{drone_id}", response_model=ResponseModel[DroneSchema])
def get_drone(
    drone_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取无人机详情"""
    drone = db.query(Drone).filter(Drone.id == drone_id).first()
    if not drone:
        raise HTTPException(
            status_code=404,
            detail="无人机不存在"
        )
    
    return ResponseModel(data=drone)

@router.post("", response_model=ResponseModel[DroneSchema])
def create_drone(
    drone_in: DroneCreate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """创建无人机"""
    # 检查无人机名称是否已存在
    drone = db.query(Drone).filter(Drone.name == drone_in.name).first()
    if drone:
        raise HTTPException(
            status_code=400,
            detail="无人机名称已存在"
        )
    
    # 检查序列号是否已存在
    drone = db.query(Drone).filter(Drone.serial_number == drone_in.serial_number).first()
    if drone:
        raise HTTPException(
            status_code=400,
            detail="序列号已存在"
        )
    
    # 检查无人机类型是否存在
    from models import DroneType
    drone_type = db.query(DroneType).filter(DroneType.id == drone_in.drone_type_id).first()
    if not drone_type:
        raise HTTPException(
            status_code=400,
            detail="无人机类型不存在"
        )
    
    # 检查操作员是否存在
    if drone_in.operator_id:
        operator = db.query(User).filter(User.id == drone_in.operator_id).first()
        if not operator:
            raise HTTPException(
                status_code=400,
                detail="操作员不存在"
            )
    
    # 检查部门是否存在
    if drone_in.department_id:
        from models import Department
        department = db.query(Department).filter(Department.id == drone_in.department_id).first()
        if not department:
            raise HTTPException(
                status_code=400,
                detail="部门不存在"
            )
    
    # 创建新无人机
    db_drone = Drone(
        name=drone_in.name,
        serial_number=drone_in.serial_number,
        drone_type_id=drone_in.drone_type_id,
        operator_id=drone_in.operator_id,
        department_id=drone_in.department_id,
        status=drone_in.status,
        latitude=drone_in.latitude,
        longitude=drone_in.longitude,
        altitude=drone_in.altitude,
        battery_level=drone_in.battery_level,
        maintenance_date=drone_in.maintenance_date
    )
    
    db.add(db_drone)
    db.commit()
    db.refresh(db_drone)
    
    return ResponseModel(data=db_drone)

@router.put("/{drone_id}", response_model=ResponseModel[DroneSchema])
def update_drone(
    drone_id: int,
    drone_in: DroneUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """更新无人机信息"""
    drone = db.query(Drone).filter(Drone.id == drone_id).first()
    if not drone:
        raise HTTPException(
            status_code=404,
            detail="无人机不存在"
        )
    
    # 检查无人机名称是否已存在（排除当前无人机）
    if drone_in.name and drone_in.name != drone.name:
        existing_drone = db.query(Drone).filter(Drone.name == drone_in.name).first()
        if existing_drone:
            raise HTTPException(
                status_code=400,
                detail="无人机名称已存在"
            )
    
    # 检查序列号是否已存在（排除当前无人机）
    if drone_in.serial_number and drone_in.serial_number != drone.serial_number:
        existing_drone = db.query(Drone).filter(Drone.serial_number == drone_in.serial_number).first()
        if existing_drone:
            raise HTTPException(
                status_code=400,
                detail="序列号已存在"
            )
    
    # 检查无人机类型是否存在
    if drone_in.drone_type_id:
        from models import DroneType
        drone_type = db.query(DroneType).filter(DroneType.id == drone_in.drone_type_id).first()
        if not drone_type:
            raise HTTPException(
                status_code=400,
                detail="无人机类型不存在"
            )
    
    # 检查操作员是否存在
    if drone_in.operator_id is not None:
        operator = db.query(User).filter(User.id == drone_in.operator_id).first()
        if not operator:
            raise HTTPException(
                status_code=400,
                detail="操作员不存在"
            )
    
    # 检查部门是否存在
    if drone_in.department_id is not None:
        from models import Department
        department = db.query(Department).filter(Department.id == drone_in.department_id).first()
        if not department:
            raise HTTPException(
                status_code=400,
                detail="部门不存在"
            )
    
    # 更新字段
    update_data = drone_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(drone, field, value)
    
    db.commit()
    db.refresh(drone)
    
    return ResponseModel(data=drone)

@router.delete("/{drone_id}", response_model=ResponseModel[dict])
def delete_drone(
    drone_id: int,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """删除无人机"""
    drone = db.query(Drone).filter(Drone.id == drone_id).first()
    if not drone:
        raise HTTPException(
            status_code=404,
            detail="无人机不存在"
        )
        
    db.delete(drone)
    db.commit()
    
    return ResponseModel(data={"message": "无人机删除成功"})

@router.put("/{drone_id}/update_status", response_model=ResponseModel[DroneSchema])
def update_drone_status(
    drone_id: int,
    status: str,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """更新无人机状态"""
    drone = db.query(Drone).filter(Drone.id == drone_id).first()
    if not drone:
        raise HTTPException(
            status_code=404,
            detail="无人机不存在"
        )
    
    valid_statuses = ["available", "busy", "maintenance", "broken"]
    if status not in valid_statuses:
        raise HTTPException(
            status_code=400,
            detail=f"无效的状态值，有效值为: {', '.join(valid_statuses)}"
        )
    
    drone.status = status
    
    # 如果状态为"busy"，更新最后飞行时间
    if status == "busy":
        drone.last_flight_time = datetime.now()
    
    db.commit()
    db.refresh(drone)
    
    return ResponseModel(data=drone)